package com.atguigu.gulimall.order.web;

import com.atguigu.common.exception.NoStockException;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponseVo;
//import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

/**
 * @author houChen
 * @date 2022/2/2 12:44
 * @Description:
 */
@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        //封装订单确认页所需的数据
        OrderConfirmVo orderConfirmVo = orderService.confirmOrder();
        model.addAttribute("orderConfirmData",orderConfirmVo);
        return "confirm";
    }

    /**
     * @Description: 提交订单
     * @param vo
     * @author  houChen
     * @date  2022/2/11 16:17
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes){
        try {
            SubmitOrderResponseVo resp = orderService.submitOrder(vo);
            if(resp.getCode() == 0){
                //创建订单成功，跳转到支付页面
                model.addAttribute("submitOrderResp",resp);
                return "pay";
            }else{
                String msg = "下单失败";
                switch (resp.getCode()){
                    case 1: msg+=":令牌校验失败，请重新确认订单"; break;
                    case 2: msg+=":订单价格发生变化，请确认后提交"; break;
                    case 3: msg+=":锁定库存失败，商品库存不足"; break;
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.gulimall.com:9010/toTrade";
            }
        } catch (NoStockException e) {
            redirectAttributes.addFlashAttribute("msg",e.getMessage());
            return "redirect:http://order.gulimall.com:9010/toTrade";
        }

    }
}